package com.akajack.test.util;

import com.akajack.test.obj.TreeNodeTest;

import java.util.LinkedList;
import java.util.Queue;

public class TreeNodeUtil {
    public static TreeNodeTest buildTree(Integer[] arr){
        if (arr.length==0) return null;
        TreeNodeTest root = new TreeNodeTest(arr[0]);
        Queue<TreeNodeTest> tnq = new LinkedList<>();
        tnq.offer(root);

        int i=1;
        while(!tnq.isEmpty()&&i<arr.length){
            TreeNodeTest node = tnq.poll();

            if (i<arr.length&&arr[i]!=null){
                node.lchild=new TreeNodeTest(arr[i]);
                tnq.offer(node.lchild);
            }
            i++;
            if (i<arr.length&&arr[i]!=null){
                node.rchild=new TreeNodeTest(arr[i]);
                tnq.offer(node.rchild);
            }
            i++;
        }
        return root;
    }

    public static String PrintTree(TreeNodeTest root){
        if (root==null) return "[]";
        String res="[";
        Queue<TreeNodeTest> tnq = new LinkedList<>();
        tnq.offer(root);

        while (!tnq.isEmpty()) {
            int levelsize = tnq.size();
            for (int i = 0; i < levelsize; i++) {
                TreeNodeTest node = tnq.poll();
                res += node.val+",";
                if (node.lchild!=null) tnq.offer(node.lchild);
                if (node.rchild!=null) tnq.offer(node.rchild);
            }
        }
        res+="end]";
        return res;
    }
}
